/*
 * @Author: szx
 * @Date: 2021-11-05 09:55:07
 * @LastEditTime: 2021-11-05 14:47:19
 * @Description:
 * @FilePath: \leetcode\1-99\94\94.cpp
 */
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

class Solution {
   public:
    void inorder(TreeNode *root, vector<int> &res) {
        if (!root) {
            return;
        }
        inorder(root->left, res);
        res.emplace_back(root->val);
        inorder(root->right, res);
    }
    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> res;
        inorder(root, res);
        return res;
    }
};

#include <stack>
class Solution {
   public:
    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> res;
        if (!root) {
            return res;
        }
        stack<TreeNode *> stk;

        TreeNode *node = root;
        while (!stk.empty() || node) {
            while (node) {
                stk.emplace(node);
                node = node->left;
            }
            node = stk.top();
            res.emplace_back(node->val);
            stk.pop();
            node = node->right;
        }
        return res;
    }
};

class Solution {
   public:
    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> res;
        if (!root) {
            return res;
        }
        TreeNode *p1 = root, *p2 = nullptr;
        while (p1) {
            p2 = p1->left;
            if (p2) {
                while (p2->right && p2->right != p1) {
                    p2 = p2->right;
                }
                if (!p2->right) {
                    p2->right = p1;
                    p1 = p1->left;
                } else {
                    res.emplace_back(p1->val);
                    p2->right = nullptr;
                    p1 = p1->right;
                }
            } else {
                res.emplace_back(p1->val);
                p1 = p1->right;
            }
        }
        return res;
    }
};